import axios from 'axios';
import { Toast } from 'antd-mobile';
import { doClean } from './StoreCache';

const LOCAL_TOKEN = 'x-domain-token';
let baseURL = 'http://localhost:18082';
// let baseURL = 'http://192.168.1.7:18082';

const instance = axios.create({
    baseURL,
    timeout: 10000,
})

instance.interceptors.request.use((config) => {
    let token = localStorage.getItem(LOCAL_TOKEN);
    let headers = {};
    if (token) {
        headers = { 'x-domain-token': token }
    }
    config.headers = {
        ...headers,
        'Content-Type': 'application/json'
    }
    config.data = JSON.stringify(config.data);
    return config;

}, (error) => {
    return Promise.reject(error);
});

instance.interceptors.response.use((resp) => {
    const code = resp.data.code;
    if (code && code === 100014) {
        doClean();
        window.location.href = "/login";
    } else {
        const token = resp.headers['x-domain-token'];
        // 更新 localStorage 中的 token，属性token, 保证token不会失效
        if (token) {
            localStorage.setItem(LOCAL_TOKEN, token);
        }
        return resp;
    }
}, (error) => {
    return Promise.reject(error);
});


export function ajax(url, data = {}, method = 'GET') {
    return new Promise((resolve, reject) => {
        let promise;
        // 1. 执行 Ajax 请求
        if (method === 'POST') {
            promise = instance.post(url, data);
        } else {
            promise = instance.get(url, { params: data });
        }
        // 2. 结果处理
        promise.then(response => {
            resolve(response);
        }).catch(error => {
            toError(error);
            reject(error);
        })
    })
}

export function download(url, params = {}, method = 'GET', fileName) {
    new Promise((resolve, reject) => {
        axios({
            url: url,
            method: method,
            params: params,
            responseType: 'blob'
        })
            .then(res => {
                let reader = new FileReader();
                let data = res.data;
                reader.onload = e => {
                    if (e.target.result.indexOf('Result') !== -1
                        && JSON.parse(e.target.result).Result === false) {
                        // 进行错误处理
                    } else {
                        if (!fileName) {
                            let contentDisposition = res.headers['content-disposition'];
                            if (contentDisposition) {
                                fileName = window.decodeURI(res.headers['content-disposition'].split('=')[2].split("''")[1], "UTF-8");
                            }
                        }
                        executeDownload(data, fileName);
                    }
                };
                reader.readAsText(data);
                resolve(res.data);
            }).catch(error => {
                reject(error);
            })
    });
}

function executeDownload(data, fileName) {
    if (!data) {
        return
    }
    let url = window.URL.createObjectURL(new Blob([data]));
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * 统一错误编号
 * @param {*} err 
 */
function toError(err) {
    if (err && err.response) {
        const { code } = err.response.data;
        switch (code) {
            case 400: Toast.show({ icon: 'fail', content: '服务异常:' + err.message }); break;
            case 500: Toast.show({ icon: 'fail', content: '服务内部异常:' + err.message }); break; 
            case 502: Toast.show({ icon: 'fail', content: '网关错误:' + err.message }); break; 
            default: break;
        }
    }
}